import {loginByUsername, logout, getUserInfo, registerUser, apiGetUserName} from '@/api/login'
import {getToken, setToken, removeToken, getVersion, setVersion, removeVersion} from '@/utils/auth'

console.log(process.env.ENV_CONFIG)

var userStore = window.localStorage

if("prod" == process.env.ENV_CONFIG) {
     userStore = window.sessionStorage
}else{

     userStore = window.localStorage
}

const user = {
    state: {
        userId: userStore.getItem("user"),
        status: false,
        code: '',
        token: getToken(),
        email:'',
        name: userStore.getItem("name"),
        avatar: userStore.getItem("avatar"),
        introduction: '',
        roles: [],
        setting: {
            articlePlatform: []
        },
        bookmarkList:[],
        version: getVersion() | 1
    },

    mutations: {
        SET_CODE: (state, code) => {
            state.code = code
        },
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_INTRODUCTION: (state, introduction) => {
            state.introduction = introduction
        },
        SET_SETTING: (state, setting) => {
            state.setting = setting
        },
        SET_STATUS: (state, status) => {
            state.status = status
        },
        SET_EMAIL: (state, email) => {
            state.email = email
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_USER_ID: (state, userId) => {
            state.userId = userId
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_VERSION: (state, version) => {
            state.version = version
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        },
        EMPTY_USER: (state) => {
            state.userId = null
            state.status = false
            state.token = null
        },
        ADD_BOOKMARK: (state, campaign) => {
            var checkrepeat = false
            state.bookmarkList.forEach(item => {
                if (item.id == campaign.id) {
                    checkrepeat = true;
                }
            })
            if(!checkrepeat) {
                state.bookmarkList.push(campaign)
            }

        }
    },

    actions: {

        SET_AVATAR: ({commit}, avatar) => {
            commit('SET_AVATAR', avatar)
        },
        ADD_BOOKMARK: ({commit}, item) => {
            commit("ADD_BOOKMARK",item)
        },
        SET_NAME: ({commit}, name) => {
            commit('SET_NAME', name)
        },

        // 用户名登录
        LoginByUsername({commit}, userInfo) {
            const username = userInfo.email.trim()

            return new Promise((resolve, reject) => {
                loginByUsername(username, userInfo.password).then(response => {
                    commit('SET_STATUS', true)
                    commit('SET_EMAIL', username)
                    commit('SET_NAME', response.userName)
                    commit('SET_USER_ID', response.userId)
                    commit('SET_TOKEN', response.token)
                    commit('SET_AVATAR', response.avatar)
                    commit('SET_VERSION', response.version)
                    setToken(response.token)
                    setVersion(response.version)

                    // 写入sessionStorage
                    window.sessionStore.setItem("status", true)
                    window.sessionStore.setItem("user", response.userId)
                    window.sessionStore.setItem("userId", response.userId)
                    window.sessionStore.setItem("name", response.userName)
                    window.sessionStore.setItem("avatar", response.avatar)
                    window.sessionStore.setItem("token", response.token)
                    window.sessionStore.setItem("version", response.version)
                    setToken(response.token)

                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetUserInfo({commit, state}) {
            return new Promise((resolve, reject) => {
                getUserInfo(state.token).then(response => {
                    if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
                        reject('error')
                    }
                    const data = response.data

                    console.log(data)

                    if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                        commit('SET_ROLES', data.roles)
                    } else {
                        reject('getInfo: roles must be a non-null array !')
                    }

                    commit('SET_NAME', data.name)
                    commit('SET_AVATAR', data.avatar)
                    commit('SET_INTRODUCTION', data.introduction)
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 第三方验证登录
        // LoginByThirdparty({ commit, state }, code) {
        //   return new Promise((resolve, reject) => {
        //     commit('SET_CODE', code)
        //     loginByThirdparty(state.status, state.email, state.code).then(response => {
        //       commit('SET_TOKEN', response.data.token)
        //       setToken(response.data.token)
        //       resolve()
        //     }).catch(error => {
        //       reject(error)
        //     })
        //   })
        // },

        // 登出
        LogOut({commit, state}) {
            return new Promise((resolve, reject) => {
                logout(state.userId).then(() => {
                    commit('EMPTY_USER')
                    removeToken()
                    removeToken()
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 前端 登出
        FedLogOut({commit}) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        },

        // 动态修改权限
        ChangeRoles({commit}, role) {
            return new Promise(resolve => {
                commit('SET_TOKEN', role)
                setToken(role)
                getUserInfo(role).then(response => {
                    const data = response.data
                    commit('SET_ROLES', data.roles)
                    commit('SET_NAME', data.name)
                    commit('SET_AVATAR', data.avatar)
                    commit('SET_INTRODUCTION', data.introduction)
                    resolve()
                })
            })
        },

        // 新用户注册
        RegisterUser({commit, state}, signUserForm) {
            return new Promise((resolve, reject) => {
                registerUser(signUserForm).then(response => {
                    if (response.code != 0) { // 由于mockjs 不支持自定义状态码只能这样hack
                        reject('error')
                    }
                    commit('SET_STATUS', true)
                    commit('SET_NAME', signUserForm.userName)

                    /*  if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                          commit('SET_ROLES', data.roles)
                      } else {
                          reject('getInfo: roles must be a non-null array !')
                      }

                      commit('SET_NAME', data.name)
                      commit('SET_AVATAR', data.avatar)
                      commit('SET_INTRODUCTION', data.introduction)*/
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 查询用户姓名
        getUserName({commit, state}, userId) {
            return new Promise((resolve, reject) => {
                apiGetUserName(userId).then(response => {
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        }
    }
}

export default user
